import ConfirmModal from '@/components/ConfirmModal';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { queryCompanies } from '@/pages/SystemUser/service';
import { Auths, Role } from '@/utils/types.d';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { message, Modal, Table, Tag } from 'antd';
import { useRef } from 'react';
import { useModel, history } from 'umi';
import CreateSensor from './components/CreateSensor';
import ExportModal from './components/ExportModal';
import HistoryModal from './components/HistoryModal';
import { deleteMulSensors, querySensorDevices, removeSensorDevice } from './service';
import type { SensorDeviceTableItem } from './types.d';

const { confirm } = Modal;
export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.sensorDevice || []) : new Set();
  const ifDelete = auths.has(Auths.DELETE);
  // const ifModify = auths.has(Auths.MODIFY);
  const ifCreate = auths.has(Auths.CREATE);
  const ifExport = auths.has(Auths.EXPORT);
  const batchTaskAuth = currUser?.auth ? new Set(currUser.auth.batchTask || []) : new Set();
  const readBatchTask = batchTaskAuth.has(Auths.READ);
  const ref = useRef<ActionType>();
  const subTitleContent = (
    <span>
      地磁设备列表，如需批量添加地磁列表，请前往
      {readBatchTask ? (
        <a
          onClick={() => {
            history.push('/batch-task');
          }}
        >
          批量任务
        </a>
      ) : (
        '批量任务'
      )}
    </span>
  );
  const columns: ProColumns<SensorDeviceTableItem>[] = [
    {
      title: 'id',
      dataIndex: '_id',
      hideInForm: true,
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '所属用户',
      dataIndex: 'ownerId',
      hideInForm: true,
      fieldProps: { showSearch: true },
      hideInTable: currUser?.role !== Role.ADMIN,
      hideInSearch: currUser?.role !== Role.ADMIN,
      render: (_, record) => record.ownerInfo?.ownerName,
      debounceTime: 300,
      request: (val) => queryCompanies(val.keyWords),
      width: 150,
    },
    {
      title: '地磁编号',
      dataIndex: 'deviceSn',
      hideInForm: true,
      align: 'center',
      width: 150,
      render: (_, record) => <HistoryModal deviceMark={record.deviceSn} />,
    },
    {
      title: '地磁厂家',
      dataIndex: 'manufacturer',
      align: 'center',
      hideInForm: true,
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
      width: 180,
    },
    {
      title: '地磁状态',
      // 字段改
      dataIndex: 'status',
      hideInForm: true,
      align: 'center',
      width: 100,
      valueEnum: {
        1: { text: <Tag color="error">有车</Tag> },
        2: { text: <Tag color="success">无车</Tag> },
        99: { text: <Tag color="default">未知</Tag> },
      },
    },
    {
      title: '在线状态',
      dataIndex: 'deviceStatus',
      hideInForm: true,
      align: 'center',
      width: 100,
      valueEnum: {
        1: { text: '离线', status: 'Error' },
        2: { text: '在线', status: 'Success' },
        99: { text: '未知', status: 'Default' },
      },
    },
    {
      title: '最近刷新时间',
      dataIndex: 'refreshTime',
      align: 'center',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
      width: 180,
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      fixed: 'right',
      width: 110,
      render: (_, record, x, action) =>
        ifDelete
          ? [
              ifDelete && (
                <ConfirmModal
                  reload={() => action?.reload()}
                  operFunc={async () => await removeSensorDevice(record._id)}
                  text={`是否确定删除地磁设备(${record.deviceSn})`}
                />
              ),
            ]
          : [<PlaceHolderCpn />],
    },
  ];
  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: subTitleContent,
        breadcrumb: {
          routes: [
            { path: '/', breadcrumbName: '首页' },
            {
              path: '/device',
              breadcrumbName: '设备管理',
            },
            {
              path: '/device/sensor',
              breadcrumbName: '地磁设备',
            },
          ],
        },
      }}
    >
      <ProTable<SensorDeviceTableItem>
        columns={columns}
        columnEmptyText="暂无数据"
        search={{
          labelWidth: 'auto',
        }}
        rowKey="_id"
        scroll={{ x: true }}
        style={{ whiteSpace: 'nowrap' }}
        dateFormatter="string"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        rowSelection={{
          selections: [Table.SELECTION_ALL],
        }}
        actionRef={ref}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <span>
            已选 {selectedRowKeys.length} 项
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
          </span>
        )}
        tableAlertOptionRender={({ selectedRowKeys, onCleanSelected }) => {
          return ifDelete ? (
            <a
              onClick={async () => {
                if (selectedRowKeys.length <= 0) {
                  message.warn({ content: '请选择需要删除的地磁', key: 'mul-remove' });
                  return false;
                }
                confirm({
                  title: '删除确认',
                  icon: <ExclamationCircleOutlined />,
                  content: '是否确认删除当前所选项',
                  onOk: async () => {
                    const res = await deleteMulSensors(selectedRowKeys as string[]);
                    ref.current?.reload();
                    if (res?.success) {
                      message.success({ content: '删除成功', key: 'mul-remove' });
                      onCleanSelected();
                      return true;
                    }
                    message.error({ content: res?.message || '删除失败', key: 'mul-remove' });
                    return false;
                  },
                });
                return false;
              }}
            >
              批量删除
            </a>
          ) : (
            <PlaceHolderCpn />
          );
        }}
        toolBarRender={(action) => [
          ifCreate && <CreateSensor reload={() => action?.reload()} />,
          ifExport && <ExportModal />,
        ]}
        debounceTime={300}
        request={async (param, sort) => {
          const res = await querySensorDevices(param, sort);
          return res;
        }}
      />
    </PageHeaderWrapper>
  );
};
